package jdbc02;

/*
* 利用PreparedStatement做CRUD
* */




import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCDemo01 {
    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=UTF-8", "root", "123456");

        // 通过连接获取执行预编译SQL的PreparedStatement
        // INSERT INTO product values (13,'良品铺子抹茶饼干',30.9,'休闲零食')
        // 预编译SQL中所有的参数都用?占位符
        PreparedStatement ps = conn.prepareStatement("INSERT INTO test.product VALUES (?, ?, ?)");
        ps.setInt(1, 13);
        ps.setString(2, "良品铺子抹茶饼干");
        ps.setDouble(3, 30.9);

        // 利用PreparedStatement接口中的executeUpdate()
        int i = ps.executeUpdate();
        System.out.println(i);

        ps.close();
        conn.close();
    }
    @Test
    public void testUpdate() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=UTF-8", "root", "123456");
        PreparedStatement ps = conn.prepareStatement("UPDATE test.product set pname=? where pid=?");
        ps.setString(1,"三只松鼠抹茶饼干");
        ps.setInt(2,13);
        // 利用PreparedStatement接口中的executeUpdate()
        int i = ps.executeUpdate();
        System.out.println(i);
        conn.close();
        ps.close();
    }
    @Test
    public void testDelete() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useSSL=false&characterEncoding=UTF-8", "root", "123456");
        PreparedStatement ps = conn.prepareStatement("delete  from  test.product  where pid=?;");
        ps.setInt(1,13);
        // 利用PreparedStatement接口中的executeUpdate()
        int i = ps.executeUpdate();
        System.out.println(i);
        conn.close();
        ps.close();
    }
}

